from django.shortcuts import render

# Create your views here.

from rest_framework.views import APIView
from rest_framework.response import Response
from django.core.paginator import Paginator
from django.utils.decorators import method_decorator
from .models import User,Org
from .serializers import Userserializers
from .utils import get_token, access_log
from .tasks import register


#序列化返回用户信息
@method_decorator(access_log, name='dispatch')#在CBV模式下为所有方法添加装饰器
class Search(APIView):
    def post(self,request):
        print(request.data)
        data={}
        org_id = request.data.get('org_id',None)
        if org_id:
            user = User.objects.get(empno=org_id)
            #序列化数据
            user_data=Userserializers(instance=user).data  
            data['code']=200
            data['message']=user_data
        else:
            data['code']=1001
            data['message']='未查找到此员工'
        return Response(data)
        

#用户登录返回token
class Login(APIView):
    def post(self, request):
        data = {}
        try:
            user = User.objects.get(name=request.data['name'])
        except:
            data['code']=1002
            data['message']='用户尚未注册'
            return Response({'code': 1002, 'message': '用户尚未注册'})
        else:
            token = get_token(user)
            data['code']=200
            data['message']='登录成功'
            data['token']=token
            return Response({'code': 200, 'message': '登录成功', 'token': token})

class Register(APIView):
    def post(self,request):
        data={}
        req_data = request.data
        print(req_data)
        user = User.objects.filter(name=req_data['name'])
        if user:
            data['code']=10010
            data['message']='该用户已注册'
        else:
            print(dir(register))
            data = register.delay(req_data)
            print(data.get())
            print(data)
        return Response(data)

